package com.study.javaFx.view;

import com.study.javaFx.model.Staff;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.application.Platform;

public class StaffView {


    
    /**
     * 显示新增员工的窗口
     */
    public void showAddWindow() {
        Stage stage = new Stage();
        stage.setTitle("新增员工");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("姓名:"), 0, 0);
        TextField nameField = new TextField();
        grid.add(nameField, 1, 0);
        grid.add(new Label("联系方式:"), 0, 1);
        TextField contactField = new TextField();
        grid.add(contactField, 1, 1);
        grid.add(new Label("职位:"), 0, 2);
        ComboBox<String> roleCombo = new ComboBox<>();
        roleCombo.getItems().addAll("机房管理员", "技术员");
        grid.add(roleCombo, 1, 2);

        Button submitBtn = new Button("提交");
        submitBtn.setOnAction(e -> {
            String name = nameField.getText().trim();
            String contact = contactField.getText().trim();
            String role = roleCombo.getValue();
            if (name.isEmpty() || contact.isEmpty() || role == null || role.isEmpty()) {
                showAlert("请填写所有字段");
                return;
            }
            Staff staff = new Staff();
            staff.setStaffId(0);
            staff.setStaffName(name);
            staff.setContact(contact);
            staff.setRole(role);
            try {
                com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String json = objectMapper.writeValueAsString(staff);
                java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create("http://localhost:8080/api/staff/add"))
                        .header("Content-Type", "application/json")
                        .POST(java.net.http.HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                java.net.http.HttpClient.newHttpClient().sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(java.net.http.HttpResponse::body)
                        .thenAccept(resp -> {
                            try {
                                // 解析后端返回，判断code
                                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                                com.fasterxml.jackson.databind.JsonNode node = mapper.readTree(resp);
                                String code = node.get("code").asText();
                                String info = node.get("info").asText();
                                if ("0000".equals(code)) {
                                    Platform.runLater(() -> {
                                        showInfoDialog("新增成功！");
                                        stage.close();
                                    });
                                } else {
                                    Platform.runLater(() -> showInfoDialog("新增失败: " + info));
                                }
                            } catch (Exception ex) {
                                Platform.runLater(() -> showAlert("返回解析失败: " + ex.getMessage()));
                            }
                        })
                        .exceptionally(ex -> { Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
            } catch (Exception ex) {
                Platform.runLater(() -> showAlert("序列化失败: " + ex.getMessage()));
            }
        });

        grid.add(submitBtn, 1, 3);
        Scene scene = new Scene(grid, 350, 220);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示修改员工的窗口
     */
    public void showUpdateWindow() {
        Stage stage = new Stage();
        stage.setTitle("修改员工");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("员工ID:"), 0, 0);
        ComboBox<Integer> idCombo = new ComboBox<>();
        grid.add(idCombo, 1, 0);
        grid.add(new Label("姓名:"), 0, 1);
        TextField staffNameField = new TextField();
        grid.add(staffNameField, 1, 1);
        grid.add(new Label("联系方式:"), 0, 2);
        TextField contactField = new TextField();
        grid.add(contactField, 1, 2);
        grid.add(new Label("职位:"), 0, 3);
        ComboBox<String> roleCombo = new ComboBox<>();
        roleCombo.getItems().addAll("机房管理员", "技术员");
        grid.add(roleCombo, 1, 3);

        Button submitBtn = new Button("提交");
        submitBtn.setDisable(true);

        // 异步加载所有员工ID
        java.net.http.HttpRequest allReq = java.net.http.HttpRequest.newBuilder()
                .uri(java.net.URI.create("http://localhost:8080/api/staff/get"))
                .GET().build();
        java.net.http.HttpClient.newHttpClient().sendAsync(allReq, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        java.util.Set<Integer> ids = new java.util.HashSet<>();
                        for (com.fasterxml.jackson.databind.JsonNode staff : dataNode) {
                            if (staff.has("staffId")) ids.add(staff.get("staffId").asInt());
                        }
                        Platform.runLater(() -> {
                            idCombo.getItems().setAll(ids);
                            if (!ids.isEmpty()) submitBtn.setDisable(false);
                        });
                    } catch (Exception ex) {
                        Platform.runLater(() -> showAlert("加载员工ID失败: " + ex.getMessage()));
                    }
                });

        // 监听下拉框选中事件，自动填充文本框
        idCombo.setOnAction(event -> {
            Integer selectedId = idCombo.getValue();
            if (selectedId == null) return;
            // 异步请求该ID的员工详细信息
            java.net.http.HttpRequest req = java.net.http.HttpRequest.newBuilder()
                    .uri(java.net.URI.create("http://localhost:8080/api/staff/get/" + selectedId))
                    .GET().build();
            java.net.http.HttpClient.newHttpClient().sendAsync(req, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                    .thenApply(java.net.http.HttpResponse::body)
                    .thenAccept(json -> {
                        try {
                            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                            com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                            com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                            if (dataNode != null && !dataNode.isNull()) {
                                String staffName = dataNode.get("staffName").asText();
                                String contact = dataNode.get("contact").asText();
                                String role = dataNode.get("role").asText();
                                Platform.runLater(() -> {
                                    staffNameField.setText(staffName);
                                    contactField.setText(contact);
                                    roleCombo.setValue(role);
                                });
                            }
                        } catch (Exception ex) {
                            Platform.runLater(() -> showAlert("加载员工详情失败: " + ex.getMessage()));
                        }
                    })
                    .exceptionally(ex -> { Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
        });

        submitBtn.setOnAction(e -> {
            Integer id = idCombo.getValue();
            String staffName = staffNameField.getText().trim();
            String contact = contactField.getText().trim();
            String role = roleCombo.getValue();
            if (id == null || staffName.isEmpty() || contact.isEmpty() || role == null || role.isEmpty()) {
                showAlert("请填写所有字段");
                return;
            }
            Staff staff = new Staff();
            staff.setStaffId(id);
            staff.setStaffName(staffName);
            staff.setContact(contact);
            staff.setRole(role);
            try {
                com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String json = objectMapper.writeValueAsString(staff);
                java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create("http://localhost:8080/api/staff/update"))
                        .header("Content-Type", "application/json")
                        .PUT(java.net.http.HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                java.net.http.HttpClient.newHttpClient().sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(java.net.http.HttpResponse::body)
                        .thenAccept(resp -> {
                            try {
                                // 解析后端返回，判断code
                                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                                com.fasterxml.jackson.databind.JsonNode node = mapper.readTree(resp);
                                String code = node.get("code").asText();
                                String info = node.get("info").asText();
                                if ("0000".equals(code)) {
                                    Platform.runLater(() -> {
                                        showInfoDialog("修改成功！");
                                        stage.close();
                                    });
                                } else {
                                    Platform.runLater(() -> showInfoDialog("修改失败: " + info));
                                }
                            } catch (Exception ex) {
                                Platform.runLater(() -> showAlert("返回解析失败: " + ex.getMessage()));
                            }
                        })
                        .exceptionally(ex -> { Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
            } catch (Exception ex) {
                Platform.runLater(() -> showAlert("序列化失败: " + ex.getMessage()));
            }
        });

        grid.add(submitBtn, 1, 4);
        Scene scene = new Scene(grid, 350, 250);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示删除员工的窗口
     */
    public void showDeleteWindow() {
        Stage stage = new Stage();
        stage.setTitle("删除员工");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("员工ID:"), 0, 0);
        ComboBox<Integer> idCombo = new ComboBox<>();
        grid.add(idCombo, 1, 0);

        Button submitBtn = new Button("删除");
        submitBtn.setDisable(true);

        // 异步加载所有员工ID
        java.net.http.HttpRequest allReq = java.net.http.HttpRequest.newBuilder()
                .uri(java.net.URI.create("http://localhost:8080/api/staff/get"))
                .GET().build();
        java.net.http.HttpClient.newHttpClient().sendAsync(allReq, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        java.util.List<Integer> ids = new java.util.ArrayList<>();
                        for (com.fasterxml.jackson.databind.JsonNode staff : dataNode) {
                            ids.add(staff.get("staffId").asInt());
                        }
                        Platform.runLater(() -> {
                            idCombo.getItems().setAll(ids);
                            if (!ids.isEmpty()) submitBtn.setDisable(false);
                        });
                    } catch (Exception ex) {
                        Platform.runLater(() -> showAlert("加载员工ID失败: " + ex.getMessage()));
                    }
                });

        submitBtn.setOnAction(e -> {
            Integer id = idCombo.getValue();
            if (id == null) {
                showAlert("请选择要删除的员工ID");
                return;
            }
            Staff staff = new Staff();
            staff.setStaffId(id);
            try {
                com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String json = objectMapper.writeValueAsString(staff);
                java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create("http://localhost:8080/api/staff/delete"))
                        .header("Content-Type", "application/json")
                        .method("DELETE", java.net.http.HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                java.net.http.HttpClient.newHttpClient().sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(java.net.http.HttpResponse::body)
                        .thenAccept(resp -> {
                            try {
                                // 解析后端返回，判断code
                                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                                com.fasterxml.jackson.databind.JsonNode node = mapper.readTree(resp);
                                String code = node.get("code").asText();
                                String info = node.get("info").asText();
                                if ("0000".equals(code)) {
                                    Platform.runLater(() -> {
                                        showInfoDialog("删除成功！");
                                        stage.close();
                                    });
                                } else {
                                    Platform.runLater(() -> showInfoDialog("删除失败: " + info));
                                }
                            } catch (Exception ex) {
                                Platform.runLater(() -> showAlert("返回解析失败: " + ex.getMessage()));
                            }
                        })
                        .exceptionally(ex -> { Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
            } catch (Exception ex) {
                Platform.runLater(() -> showAlert("序列化失败: " + ex.getMessage()));
            }
        });

        grid.add(submitBtn, 1, 1);
        Scene scene = new Scene(grid, 350, 150);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 弹窗方式显示查询员工界面，仿照MachineView实现
     */
    public void showQueryWindow() {
        Stage dialog = new Stage();
        dialog.setTitle("查询员工");
        dialog.initModality(javafx.stage.Modality.APPLICATION_MODAL);

        TableView<com.study.javaFx.model.Staff> table = new TableView<>();
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        TableColumn<com.study.javaFx.model.Staff, Number> idCol = new TableColumn<>("员工ID");
        idCol.setCellValueFactory(cellData -> cellData.getValue().staffIdProperty());
        TableColumn<com.study.javaFx.model.Staff, String> staffNameCol = new TableColumn<>("姓名");
        staffNameCol.setCellValueFactory(cellData -> cellData.getValue().staffNameProperty());
        TableColumn<com.study.javaFx.model.Staff, String> contactCol = new TableColumn<>("联系方式");
        contactCol.setCellValueFactory(cellData -> cellData.getValue().contactProperty());
        TableColumn<com.study.javaFx.model.Staff, String> roleCol = new TableColumn<>("职位");
        roleCol.setCellValueFactory(cellData -> cellData.getValue().roleProperty());
        table.getColumns().setAll(idCol, staffNameCol, contactCol, roleCol);

        // 查询面板
        GridPane queryPane = new GridPane();
        queryPane.setPadding(new Insets(10));
        queryPane.setHgap(10);
        queryPane.setVgap(10);
        queryPane.add(new Label("输入员工ID:"), 0, 0);
        TextField idField = new TextField();
        queryPane.add(idField, 1, 0);
        Button queryBtn = new Button("查询");
        queryPane.add(queryBtn, 2, 0);

        // 定义后端基础URL、httpClient和objectMapper
        String BASE_URL = "http://localhost:8080/api/staff";
        java.net.http.HttpClient httpClient = java.net.http.HttpClient.newHttpClient();
        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();

        // 初始加载全部员工数据
        System.out.println("请求全部员工数据: " + BASE_URL + "/get");
        java.net.http.HttpRequest allRequest = java.net.http.HttpRequest.newBuilder().uri(java.net.URI.create(BASE_URL + "/get")).GET().build();
        httpClient.sendAsync(allRequest, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
            .thenApply(java.net.http.HttpResponse::body)
            .thenAccept(json -> {
                try {
                    System.out.println("后端返回原始数据: " + json);
                    com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                    com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                    java.util.List<com.study.javaFx.model.Staff> staffs = objectMapper.readValue(dataNode.traverse(), new com.fasterxml.jackson.core.type.TypeReference<java.util.List<com.study.javaFx.model.Staff>>(){});
                    javafx.collections.ObservableList<com.study.javaFx.model.Staff> data = javafx.collections.FXCollections.observableArrayList(staffs);
                    Platform.runLater(() -> table.setItems(data));
                } catch (Exception ex) {
                    System.out.println("JSON解析异常: " + ex.getMessage());
                    Platform.runLater(() -> showAlert("初始化数据失败: " + ex.getMessage()));
                }
            })
            .exceptionally(ex -> { Platform.runLater(() -> showAlert("初始化请求失败: " + ex.getMessage())); return null; });

        // 查询按钮事件
        queryBtn.setOnAction(e -> {
            String idText = idField.getText().trim();
            if (idText.isEmpty()) {
                showAlert("请输入要查询的员工ID");
                return;
            }
            System.out.println("请求单个员工，id参数: " + idText);
            String url = BASE_URL + "/get/" + idText;
            java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder().uri(java.net.URI.create(url)).GET().build();
            httpClient.sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        System.out.println("后端返回原始数据: " + json);
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        com.study.javaFx.model.Staff staff = objectMapper.readValue(dataNode.traverse(), com.study.javaFx.model.Staff.class);
                        java.util.List<com.study.javaFx.model.Staff> staffs = new java.util.ArrayList<>();
                        if (staff != null) staffs.add(staff);
                        javafx.collections.ObservableList<com.study.javaFx.model.Staff> data = javafx.collections.FXCollections.observableArrayList(staffs);
                        Platform.runLater(() -> table.setItems(data));
                    } catch (Exception ex) {
                        System.out.println("JSON解析异常: " + ex.getMessage());
                        Platform.runLater(() -> showAlert("解析数据失败: " + ex.getMessage()));
                    }
                })
                .exceptionally(ex -> { Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
        });

        VBox vbox = new VBox(queryPane, table);
        vbox.setPadding(new Insets(10));
        Scene scene = new Scene(vbox, 600, 400);
        dialog.setScene(scene);
        dialog.showAndWait();
    }

    /**
     * 显示错误弹窗
     */
    private void showAlert(String msg) {
        Platform.runLater(() -> new Alert(Alert.AlertType.ERROR, msg).showAndWait());
    }

    /**
     * 显示标准信息弹窗
     * @param msg 提示信息
     */
    private void showInfoDialog(String msg) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("消息");
            alert.setHeaderText(null);
            alert.setContentText(msg);
            alert.showAndWait();
        });
    }
} 